import { addCategory, getCategoryDetail } from '@/services/api';
import {
  DrawerForm,
  ProFormDigitRange,
  ProFormGroup,
  ProFormInstance,
  ProFormRadio,
  ProFormText,
  ProFormTimePicker,
} from '@ant-design/pro-components';
import { useRequest } from 'ahooks';
import { Form, message } from 'antd';
import dayjs from 'dayjs';
import { isEqual } from 'lodash';
import React, { useEffect, useMemo, useRef } from 'react';

interface Props {
  open?: boolean;
  onClose?: () => void;
  onFinish?: () => void;
  title?: string;
  oid?: string;
}

const AddCatrgoryDrawer: React.FC<Props> = ({
  open,
  onClose,
  title,
  oid,
  onFinish,
}) => {
  const [form] = Form.useForm<any>();

  const formRef = useRef<ProFormInstance>();

  // 是否新增
  const isAdd = useMemo(() => {
    return !oid;
  }, [oid]);

  const { run, loading } = useRequest(
    async () => {
      return await getCategoryDetail({
        oid: oid,
      });
    },
    {
      manual: true,
      onSuccess: (data) => {
        form.setFieldsValue({
          ...data,
          time: [
            dayjs(data?.startTime, 'HH:mm'),
            dayjs(data?.endTime, 'HH:mm'),
          ],
          needPO: data?.needPO === 'true',
          hidden: data?.hidden === 'true',
          noDiscount: data?.noDiscount === 'true',
          noMark: data?.noMark === 'true',
          quickSelect: data?.quickSelect === 'true',
          selectOption: data?.selectOption === 'true',
          totalMark: data?.totalMark === 'true',
          date: [data?.startDate, data?.endDate],
        });
      },
    },
  );

  useEffect(() => {
    if (oid) {
      run();
    }
  }, [oid]);

  return (
    <DrawerForm
      formRef={formRef}
      title={title}
      form={form}
      open={open}
      width={'38%'}
      onOpenChange={(visible) => {
        if (!visible) {
          onClose?.();
        }
      }}
      autoFocusFirstInput
      drawerProps={{
        destroyOnClose: true,
        loading: loading,
      }}
      onFinish={async (values) => {
        try {
          await addCategory({
            ...values,
            startTime: values?.time?.[0],
            endTime: values?.time?.[1],
            startDate: values?.date?.[0],
            endDate: values?.date?.[1],
            action: isAdd ? 'insertProductCategory' : 'updateProductCategory',
            oid: isAdd ? undefined : oid,
          });

          message.success(`${isAdd ? '新增類別成功' : '更新類別成功'}`);

          onFinish?.();
        } catch (error) {}

        // 如果是新增
        message.success('提交成功');
        return true;
      }}
    >
      <ProFormText
        name="name"
        label="名稱"
        rules={[
          {
            required: true,
            message: '請輸入名稱',
          },
        ]}
        placeholder="請輸入名稱"
      />

      <ProFormDigitRange
        label="開始日期-結束日期"
        name="date"
        rules={[
          {
            required: true,
            message: '請輸入開始日期-結束日期',
          },
        ]}
      />

      <ProFormTimePicker.RangePicker
        name="time"
        label="開始時間-結束時間"
        rules={[
          {
            required: true,
            message: '請輸入開始時間-結束時間',
          },
        ]}
        fieldProps={{
          format: 'HH:mm',
        }}
      />

      <ProFormGroup>
        <ProFormRadio.Group
          name="needPO"
          label="需要入貨"
          options={[
            {
              label: '是',
              value: true,
            },
            {
              label: '否',
              value: false,
            },
          ]}
          rules={[
            {
              required: true,
              message: '請選擇是否需要入貨',
            },
          ]}
        />

        <ProFormRadio.Group
          name="noDiscount"
          label="不再折扣"
          options={[
            {
              label: '是',
              value: true,
            },
            {
              label: '否',
              value: false,
            },
          ]}
          rules={[
            {
              required: true,
              message: '請選擇是否不再折扣',
            },
          ]}
        />
      </ProFormGroup>
      <ProFormGroup>
        <ProFormRadio.Group
          name="hidden"
          label="散叫隱藏"
          options={[
            {
              label: '是',
              value: true,
            },
            {
              label: '否',
              value: false,
            },
          ]}
          rules={[
            {
              required: true,
              message: '請選擇是否散叫隱藏',
            },
          ]}
        />
        <ProFormRadio.Group
          name="quickSelect"
          label="快速選擇"
          options={[
            {
              label: '是',
              value: true,
            },
            {
              label: '否',
              value: false,
            },
          ]}
          rules={[
            {
              required: true,
              message: '請選擇是否快速選擇',
            },
          ]}
        />
      </ProFormGroup>

      <ProFormGroup>
        <ProFormRadio.Group
          name="noMark"
          label="不列入積分"
          options={[
            {
              label: '是',
              value: true,
            },
            {
              label: '否',
              value: false,
            },
          ]}
          rules={[
            {
              required: true,
              message: '請選擇是否不列入積分',
            },
          ]}
        />

        <ProFormRadio.Group
          name="totalMark"
          label="總額積分計算"
          options={[
            {
              label: '是',
              value: true,
            },
            {
              label: '否',
              value: false,
            },
          ]}
          rules={[
            {
              required: true,
              message: '請選擇是否總額積分計算',
            },
          ]}
        />
      </ProFormGroup>

      <ProFormRadio.Group
        name="selectOption"
        label="選項顯示另一視窗選擇"
        options={[
          {
            label: '是',
            value: true,
          },
          {
            label: '否',
            value: false,
          },
        ]}
        rules={[
          {
            required: true,
            message: '請選擇是否選項顯示另一視窗選擇',
          },
        ]}
      />
    </DrawerForm>
  );
};

export default React.memo(AddCatrgoryDrawer, (prev, next) =>
  isEqual(prev, next),
);
